# -*- coding:utf-8 -*-
# 不要改这个文件

import numpy as np
import pyautogui
import time
import cv2
import bao_sys

# pyautogui 系统配置
pyautogui.PAUSE = 1
pyautogui.FAILSAFE = True

# 图像路径配置
limit = 10000
file_head = 'baokemeng/'
screenshot_picture = 'screenshot.png'
file_ball = 'ball31.png'
file_array = ['CreatRoom.png', 'BeginGame.png', 'enter.png', 'level2.png', 'ring.png', 'map.png', 'ball30.png',
              # 删除'',
              'map.png', 'SelectBB.png']  # '2ball.png', 'map.png', 'SelectBB.png'  移除'SelBB.png'
file_exit_array = ['exit1.png', 'exit2.png', 'exit4.png', 'exit5.png']
file_begin_game = 'CreatGame.png'
#               , '2ball.png']

# 变量定义
# 脚本运行时间内游戏启动次数
# game_count = 0
# 单次匹配内重匹配次数
count_retry = 0
# 近似值
similarity = 0.95
# selectBB标志位
selectBB = 0
# X Y坐标
BB_x = 0
BB_y = 0
Ball_x = 0  # 记录BB球地址
Ball_y = 0
Roll_x = 0  # 记录BB球地图位置
Roll_y = 0
Map_x = 0  # 记录selectBB位置
Map_y = 0


# 图像金字塔是一种多尺度表示图像的方法，可以通过在不同分辨率下对图像进行缩放来提高匹配的准确性
def pyramid(image, scale=1.5, minSize=(30, 30)):
    yield image
    while True:
        width = int(image.shape[1] / scale)
        image = cv2.resize(image, (width, width))
        if image.shape[0] < minSize[1] or image.shape[1] < minSize[0]:
            break
        yield image

# 增加一个是否使用pyramid参数默认为false
def get_location(target_image, sample_image, threshold=0.9, if_pyramid=False):
    screen = pyautogui.screenshot()
    screen_np = np.array(screen)
    screen_gray = cv2.cvtColor(screen_np, cv2.COLOR_BGR2GRAY)
    print("here2")
    template = cv2.imread(target_image, 0)

    best_match = None
    best_scale = 0
    best_threshold = 0
    print("here2")
    # while
    # TODO 待增加置信度的使用 如果达不到一定的置信度就返回none
    for scale in np.arange(bao_sys.scale_image_up, bao_sys.scale_image_down, bao_sys.compare):  # 从100%到60%缩放比例
        template_resized = cv2.resize(template, None, fx=scale, fy=scale)
        w, h = template_resized.shape[::-1]
        if if_pyramid:
            for resized in pyramid(screen_gray, scale=1.5, minSize=(w, h)):
                if resized.shape[0] < h or resized.shape[1] < w:
                    break
                # print(scale)
                res = cv2.matchTemplate(screen_gray, template_resized, cv2.TM_CCOEFF_NORMED)
                # threshold = 0.7
                loc = np.where(res >= threshold)

                for pt in zip(*loc[::-1]):
                    if best_match is None or res[pt[1], pt[0]] > best_threshold:
                        best_match = pt[0] + w // 2, pt[1] + h // 2
                        best_scale = scale
                        best_threshold = res[pt[1], pt[0]]
        else:
            res = cv2.matchTemplate(screen_gray, template_resized, cv2.TM_CCOEFF_NORMED)
            # threshold = 0.7
            loc = np.where(res >= threshold)

            for pt in zip(*loc[::-1]):
                if best_match is None or res[pt[1], pt[0]] > best_threshold:
                    best_match = pt[0] + w // 2, pt[1] + h // 2
                    best_scale = scale
                    best_threshold = res[pt[1], pt[0]]
    # print()

    if best_match is None or best_scale is None or best_threshold < threshold:
        print(best_scale)
        return None
    else:
        return best_match, best_scale

# 遇到的问题: 11对战平台应该是有防止自动脚本的,管理员身份运行
# 屏幕尺寸 1920 1080
# 创建房间鼠标大概位置 1121 181
# 下一步 实现发现没有点击到红球或者出现其他错误时 直接退出游戏重新开始，对应图片已截图   红球大概范围 1548 755 超出这个范围就视为出现bug可以重新开始游戏 或者难度选择错误选择了难度4或更高难度
# 完成游戏页面未截图 先完成一个球的test，然后再考虑两个球的问题
def baoKeMengRun():
    print("baokemengV2.0")
    global BB_x, BB_y, Roll_x, Ball_x, Ball_y, Roll_y, Map_x, Map_y
    count_retry = 0
    while True:
        time.sleep(2)
        # print("begin")
        for i in range(0, 9):
            x = 0
            y = 0
            # file_name_exit = file_head + file_exit_array[i]
            file_name = file_head + file_array[i]
            # Todo 对于简单的图片可以使用pyautogui提供的API进行识别
            res = get_location(file_name, screenshot_picture, threshold=bao_sys.threshold)
            while res is None:
                if i == 8:
                    res = get_location(file_name, screenshot_picture, threshold=bao_sys.threshold-0.2)
                elif i == 2:
                    res = pyautogui.locateOnScreen(file_name, confidence=0.8)
                else:
                    res = get_location(file_name, screenshot_picture, threshold=bao_sys.threshold)
                count_retry += 1
                print('count_retry times:', count_retry, "pic:", i)
            # time.sleep(1)

            if res is not None:
                if i != 2:
                    position, scale = res
                    x, y = position
                    print(scale)
                else:
                    x, y = pyautogui.center(res)
                # if scale > bao_sys.scale:
                print(x, y)
                if i < 2:
                    print("创建游戏或开始游戏")
                    pyautogui.leftClick(x, y)
                elif i == 2:
                    print("识别是否已经进入地图")
                    continue
                elif i == 3:
                    print("选择难度")
                    pyautogui.moveTo(x, y)
                    pyautogui.leftClick(x, y)
                elif i == 4:
                    print("腾空物品栏")
                    BB_x = x - bao_sys.panel_x
                    BB_y = y - bao_sys.panel_y
                    pyautogui.moveTo(BB_x, BB_y)
                    pyautogui.leftClick(BB_x, BB_y)
                    pyautogui.leftClick(BB_x, BB_y)
                elif i == 5:
                    print("移动地图以确保视野内存在红球")
                    Roll_x = x + bao_sys.Roll_Map_x
                    Roll_y = y + bao_sys.Roll_Map_y
                    pyautogui.moveTo(Roll_x, Roll_y)
                    pyautogui.leftClick(Roll_x, Roll_y)
                    print("Roll:", Roll_x, Roll_y)
                    print("Rollxy:", x, y)
                    # pyautogui.leftClick(x + 35, y + 45)

                elif i == 6:
                    print("识别红球")
                    pyautogui.rightClick(x, y)
                    pyautogui.rightClick(x, y)
                    print("拾取红球")
                    Ball_x = x
                    Ball_y = y
                    print("记录红球xy值以便下一个球的拾取")
                elif i == 7:
                    pyautogui.moveTo(x + bao_sys.Map_x, y - bao_sys.Map_y)
                    pyautogui.leftClick(x + bao_sys.Map_x, y - bao_sys.Map_y)
                    print("移动地图以选择BB")
                    Map_x = x + bao_sys.Map_x
                    Map_y = y - bao_sys.Map_y

                elif i == 8:
                    print("移动到物品栏使用红球")
                    pyautogui.moveTo(BB_x, BB_y)
                    pyautogui.leftClick(BB_x, BB_y)
                    print("选择BB")
                    pyautogui.moveTo(x + bao_sys.Select_BB1_x, y + bao_sys.Select_BB1_y)
                    pyautogui.leftClick(x + bao_sys.Select_BB1_x, y + bao_sys.Select_BB1_y)

                    print("重复捡球与选择BB")
                    pyautogui.moveTo(Roll_x, Roll_y)
                    pyautogui.leftClick(Roll_x, Roll_y)
                    print("移动MAP以进行第二个BB球抓取")
                    pyautogui.rightClick(Ball_x, Ball_y)
                    pyautogui.rightClick(Ball_x, Ball_y)
                    time.sleep(1)
                    print("拾取红球")
                    pyautogui.moveTo(Map_x, Map_y)
                    pyautogui.leftClick(Map_x, Map_y)
                    print("移动地图以选择BB")

                    print("移动到物品栏使用红球")
                    pyautogui.moveTo(BB_x, BB_y)
                    pyautogui.leftClick(BB_x, BB_y)
                    print("选择BB")
                    pyautogui.moveTo(x + bao_sys.Select_BB2_x, y + bao_sys.Select_BB2_y)
                    pyautogui.leftClick(x + bao_sys.Select_BB2_x, y + bao_sys.Select_BB2_y)

                elif i == 9:
                    print("等待游戏成功或失败进行识别退出")
            else:
                print("none")
                #  TODO 如果时间超过10s没有选择 那么就退出游戏重新开始

        while True:
            game_exit = 0
            for j in range(0, 4):
                file_name_exit = file_head + file_exit_array[j]
                print("正在识别退出 ", j)
                res = get_location(file_name_exit, screenshot_picture, bao_sys.threshold)

                if res is not None:  # 每次都识别一次是否需要退出游戏
                    time.sleep(1)
                    print('退出', j)
                    position, scale = res
                    x1, y1 = position
                    pyautogui.moveTo(x1, y1)
                    pyautogui.leftClick(x1, y1)
                    # print('game_count:', game_count)
                    if j == 1:
                        game_exit = 1
                        # game_count += 1
            if game_exit == 1:
                break
        time.sleep(20)

